import {storeBindingsBehavior} from "mobx-miniprogram-bindings";
import mall from "@src/store/mall";
import location from "@src/store/location";
import router from "@src/router";
import {getAddressList} from "@src/api/mall/address";
import base from "@src/store/base";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: location,
    fields: ['auth'],
  }, {
    store: mall,
    fields: ['curLocation', 'userLocation', 'chooseLocation'],
    actions: ['initLocation', 'setStoreId']
  }, {
    store: base,
    fields: ['themeColor', 'themeTitleColor']
  }],
  data: {
    addressList: null
  },
  lifetimes: {
    ready: function () {
      this.fetchData();
    },
  },
  pageLifetimes: {
    show: function() {
      this.fetchData();
    },
  },
  methods: {
    fetchData() {
      getAddressList().then(res => {
        this.setData({
          addressList: res.data
        })
      })
    },
    handleSelectAddress(e) {
      const address = e.currentTarget.dataset.address
      let data = {
        address: address,
        deliveryType: 'LOCAL'
      }
      this.triggerEvent('address', data);
    },
    handleAddAddress() {
      router.push({name: "mall/address-form", params: {mode: 'add'}})
    },
    handleEditAddress(e) {
      let address = e.currentTarget.dataset.address
      router.push({name: "mall/address-form",
        params: {mode: 'edit'},
        success: (res)=> {
          res.eventChannel.emit('form', { form: address })
        }
      })
    },
  }
});
